package cn.jiyun.service.impl;


import cn.jiyun.common.R;
import cn.jiyun.dao.CategoryDao;
import cn.jiyun.dao.DishDao;
import cn.jiyun.exption.Flexption;
import cn.jiyun.exption.NameExption;
import cn.jiyun.pojo.Category;
import cn.jiyun.pojo.Dish;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class CategorySerivce implements cn.jiyun.service.CategorySerivce {
    @Resource
    private CategoryDao categoryDao;

    @Resource
    private DishDao dishDao;



    @Override
    public R page(Page<Category> page1) {
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.orderByDesc(Category::getSort);
        Page<Category> categoryPage = categoryDao.selectPage(page1, qw);
        return R.success(categoryPage);
    }

    @Override
    public R add(Category category) {
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.eq(Category::getName,category.getName());
        Category one = categoryDao.selectOne(qw);
        if (one!=null){
            throw new NameExption(category.getName());
        }

        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        int c = categoryDao.insert(category);
        if (c>0){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @Override
    public R update(Category category) {
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.eq(Category::getName,category.getName());
        Category one = categoryDao.selectOne(qw);
        if (one!=null){
            throw new NameExption(category.getName());
        }
        category.setUpdateTime(LocalDateTime.now());
        int c = categoryDao.updateById(category);
        if (c>0){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    @Override
    public R delete(Long id) {
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,id);
        Category category = categoryDao.selectById(id);
        List<Dish> dishes = dishDao.selectList(qw);
        if (!dishes.isEmpty()){
            throw  new Flexption(category.getName());
        }else {
            return R.success(categoryDao.deleteById(id));
        }



    }

    @Override
    public List<Category> findAll() {
        return categoryDao.selectList(null);
    }

    @Override
    public List<Category> list() {
//        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
//        qw.eq(Category::getId,categoryId);
        return categoryDao.selectList(null);
    }
}
